package com.llyb.chap03;

class print{
    private Integer num=0;

    public synchronized void increase() throws InterruptedException {
        while (num !=0){ // 不能使用if
            wait();
        }
        System.out.println(Thread.currentThread().getName()+"num++后为    "+ ++num);
        notifyAll();
    }

    public synchronized void decrease() throws InterruptedException {
        while (num!=1){
            wait();
        }
        System.out.println(Thread.currentThread().getName()+ "num--后为              "+ --num);
        notifyAll();
    }

}
public class WaitAndNotify {


    public static void main(String[] args) {

        print print = new print();

        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                try {
                    print.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },("BB")).start();
        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                try {
                    print.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },("DD")).start();

        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                try {
                    print.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },("AA")).start();



        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                try {
                    print.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },("CC")).start();


    }
}
